<template>
    <div class="content">
        <el-tabs type="border-card" class="custom-tabs">
            <el-tab-pane label="酒店入驻">
                <el-form ref="hotelFormRef" :model="hotelForm" :rules="hotelRules" label-width="120px" size="default"
                    class="settled-form">
                    <el-form-item label="酒店名称" prop="hotelName">
                        <el-input v-model="hotelForm.hotelName" placeholder="请输入酒店名称" />
                    </el-form-item>
                    <el-form-item label="所在地区" prop="region">
                        <div class="region-selectors">
                            <el-select v-model="hotelForm.province" @change="fetchCities" placeholder="选择省">
                                <el-option v-for="province in provinces" :key="province.id" :label="province.name"
                                    :value="province.area_id" />
                            </el-select>
                            <el-select v-model="hotelForm.city" @change="fetchDistricts" placeholder="选择市"
                                :disabled="!hotelForm.province">
                                <el-option v-for="city in cities" :key="city.id" :label="city.name"
                                    :value="city.area_id" />
                            </el-select>
                            <el-select v-model="hotelForm.district" placeholder="选择区/县" :disabled="!hotelForm.city"
                                @change="handleDistrictChange">
                                <el-option v-for="district in districts" :key="district.id" :label="district.name"
                                    :value="district.area_id" />
                            </el-select>
                        </div>
                    </el-form-item>
                    <el-form-item label="酒店详细地址" prop="hotelAddress">
                        <el-input v-model="hotelForm.hotelAddress" placeholder="请输入酒店地址" />
                    </el-form-item>
                    <el-form-item label="联系电话" prop="hotelPhone">
                        <el-input v-model="hotelForm.hotelPhone" placeholder="请输入联系电话" />
                    </el-form-item>
                    <el-form-item label="酒店简介" prop="hotelDesc">
                        <el-input v-model="hotelForm.hotelDesc" type="textarea" :maxlength="maxDescLength"
                            show-word-limit placeholder="请输入酒店简介" />
                    </el-form-item>
                    <el-form-item label="联系人" prop="hotelContext">
                        <el-input v-model="hotelForm.hotelContext" placeholder="请输入联系人" />
                    </el-form-item>
                    <!-- <el-form-item label="相关资质材料" prop="qualification">
                        <el-upload action="your-upload-url" list-type="text" v-model:file-list="hotelForm.qualification"
                            :auto-upload="false" :on-change="handleImageChange" :on-preview="handleImagePreview">
                            <el-button type="primary">上传资质材料</el-button>
                        </el-upload>
                    </el-form-item> -->
                    <el-form-item label="相关图片" prop="hotelImage">
                        <el-upload action="your-upload-url" list-type="picture-card"
                            v-model:file-list="hotelForm.hotelImage" :auto-upload="false" :on-change="handleImageChange"
                            :on-preview="handleImagePreview" :on-remove="handleImageRemove" multiple :limit="5"
                            accept=".jpg,.jpeg,.png,.gif">
                            <i class="el-icon-plus"></i>
                            <template #tip>
                                <div class="el-upload__tip">
                                    支持 jpg/png/gif 格式图片，单个文件不超过 2MB，最多上传 5 张
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                    <!-- 添加图片预览对话框 -->
                    <el-dialog v-model="dialogVisible" title="预览图片">
                        <img :src="dialogImageUrl" alt="Preview Image" style="width: 100%">
                    </el-dialog>
                    <el-form-item class="form-buttons">
                        <el-button type="primary" @click="submitHotelForm" class="submit-btn">提交申请</el-button>
                        <el-button @click="resetHotelForm" class="reset-btn">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>

            <el-tab-pane label="旅社入驻">
                <el-form ref="travelFormRef" :model="travelForm" :rules="hostelRules" label-width="120px" size="default"
                    class="settled-form">
                    <el-form-item label="旅社名称" prop="travelName">
                        <el-input v-model="travelForm.travelName" placeholder="请输入旅社名称" />
                    </el-form-item>
                    <el-form-item label="所在地区" prop="region">
                        <div class="region-selectors">
                            <el-select v-model="travelForm.province" @change="fetchCities1" placeholder="选择省">
                                <el-option v-for="province in provinces" :key="province.id" :label="province.name"
                                    :value="province.area_id" />
                            </el-select>
                            <el-select v-model="travelForm.city" @change="fetchDistricts1" placeholder="选择市"
                                :disabled="!travelForm.province">
                                <el-option v-for="city in cities" :key="city.id" :label="city.name"
                                    :value="city.area_id" />
                            </el-select>
                            <el-select v-model="travelForm.district" placeholder="选择区/县" :disabled="!travelForm.city" @change="handleDistrictChange1">
                                <el-option v-for="district in districts" :key="district.id" :label="district.name"
                                    :value="district.area_id" />
                            </el-select>
                        </div>
                    </el-form-item>
                    <el-form-item label="旅社地址" prop="travelAddress">
                        <el-input v-model="travelForm.travelAddress" placeholder="请输入旅社地址" />
                    </el-form-item>
                    <el-form-item label="联系电话" prop="travelPhone">
                        <el-input v-model="travelForm.travelPhone" placeholder="请输入联系电话" />
                    </el-form-item>
                    <el-form-item label="旅社简介" prop="travelDesc">
                        <el-input v-model="travelForm.travelDesc" :maxlength="maxDescLength" type="textarea"
                            show-word-limit placeholder="请输入旅社简介" />
                    </el-form-item>
                    <el-form-item label="联系人" prop="travelContext">
                        <el-input v-model="travelForm.travelContext" placeholder="请输入联系人" />
                    </el-form-item>
                    <!-- <el-form-item label="相关资质材料" prop="qualification">
                        <el-upload action="your-upload-url" list-type="text"
                            v-model:file-list="hostelForm.qualification" :auto-upload="false"
                            :on-change="handleImageChange" :on-preview="handleImagePreview">
                            <el-button type="primary">上传资质材料</el-button>
                        </el-upload>
                    </el-form-item> -->
                    <el-form-item label="相关图片" prop="travelImage">
                        <el-upload action="your-upload-url" list-type="picture-card"
                            v-model:file-list="travelForm.travelImage" :auto-upload="false"
                            :on-change="handleImageChange">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    <!-- 添加图片预览对话框 -->
                    <el-dialog v-model="dialogVisible" title="预览图片">
                        <img :src="dialogImageUrl" alt="Preview Image" style="width: 100%">
                    </el-dialog>
                    <el-form-item class="form-buttons">
                        <el-button type="primary" @click="submitTravelForm" class="submit-btn">提交申请</el-button>
                        <el-button @click="resetHostelForm" class="reset-btn">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { $locationList } from '../../api/location'
import { $addHotel } from '../../api/hotel'
import { $addTravel } from '../../api/travel'

// 表单引用
const hotelFormRef = ref<FormInstance>()
const travelFormRef = ref<FormInstance>()
const provinces = ref<any[]>([])
const cities = ref<any[]>([])
const districts = ref<any[]>([])

// 酒店表单数据
const hotelForm = reactive({
    hotelName: '',
    province: '',
    city: '',
    district: '',
    hotelAddress: '',
    hotelPhone: '',
    hotelDesc: '',
    hotelContext: '',
    qualification: [],
    hotelImage: []
})

// 旅社表单数据
const travelForm = reactive({
    travelName: '',
    province: '',
    city: '',
    district: '',
    address: '',
    phone: '',
    description: '',
    contactPerson: '',
    qualification: [],
    travelImage: []
})

// 验证规则
const validatePhone = (rule: any, value: string, callback: any) => {
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!value) {
        callback(new Error('请输入联系电话'))
    } else if (!phoneRegex.test(value)) {
        callback(new Error('请输入正确的手机号码'))
    } else {
        callback()
    }
}

const rules = {
    hotelName: [
        { required: true, message: '请输入酒店名称', trigger: 'blur' },
    ],
    travelName: [
        { required: true, message: '请输入旅社名称', trigger: 'blur' },
    ],
    province: [
        { required: true, message: '请选择省份', trigger: 'change' }
    ],
    city: [
        { required: true, message: '请选择城市', trigger: 'change' }
    ],
    district: [
        { required: true, message: '请选择区/县', trigger: 'change' }
    ],
    hotelAddress: [
        { required: true, message: '请输入地址', trigger: 'blur' },
    ],
    travelAddress: [
        { required: true, message: '请输入地址', trigger: 'blur' },
    ],
    hotelPhone: [
        { required: true, trigger: 'blur', validator: validatePhone }
    ],
    travelPhone: [
        { required: true, trigger: 'blur', validator: validatePhone }
    ],
    hotelDesc: [
        { required: true, message: '请输入简介', trigger: 'blur' },
    ],
    travelDesc: [
        { required: true, message: '请输入简介', trigger: 'blur' },
    ],
    hotelContext: [
        { required: true, message: '请输入联系人', trigger: 'blur' },
    ],
    travelContext: [
        { required: true, message: '请输入联系人', trigger: 'blur' },
    ],
    // qualification: [
    //     { required: true, message: '请上传资质材料', trigger: 'blur' },
    // ],
    image: [
        { required: true, message: '请上传图片', trigger: 'blur' },
    ]
}

const hotelLocation = reactive({
    provinceLocation: '',
    cityLocation: '',
    regionLocation: ''
})

const travelLocation = reactive({
    provinceLocation: '',
    cityLocation: '',
    regionLocation: ''
})

// 添加获取地区数据的方法
const fetchProvinces = async () => {
    // TODO: 调用API获取省份数据
    try {
        const response = await $locationList({ id: 0 })
        provinces.value = response.data;
        console.log(provinces.value);

        hotelForm.city = '';
        hotelForm.district = '';
        districts.value = [];  // 清空区县数据   
    } catch (error) {
        console.error('获取城市数据失败:', error);
    }
}

const fetchProvinces1 = async () => {
    // TODO: 调用API获取省份数据
    try {
        const response = await $locationList({ id: 0 })
        provinces.value = response.data;
        console.log(provinces.value);

        travelForm.city = '';
        travelForm.district = '';
        districts.value = [];  // 清空区县数据   
    } catch (error) {
        console.error('获取城市数据失败:', error);
    }
}

const fetchCities = async (provinceId: string) => {
    // TODO: 调用API获取城市数据
    try {
        const response = await $locationList({ id: provinceId })
        cities.value = response.data
        hotelLocation.provinceLocation = provinces.value[provinceId].name
        console.log(hotelLocation.provinceLocation);

        hotelForm.city = '';
        hotelForm.district = '';
        districts.value = [];
        // 清空市区名称
        hotelLocation.cityLocation = ''
    } catch (error) {
        console.error('获取城市数据失败:', error);
    }
}

const fetchCities1 = async (provinceId: string) => {
    // TODO: 调用API获取城市数据
    try {
        const response = await $locationList({ id: provinceId })
        cities.value = response.data
        travelLocation.provinceLocation = provinces.value[provinceId].name
        console.log(hotelLocation.provinceLocation);

        travelForm.city = '';
        travelForm.district = '';
        districts.value = [];
        // 清空市区名称
        hotelLocation.cityLocation = ''
    } catch (error) {
        console.error('获取城市数据失败:', error);
    }
}

const fetchDistricts = async (cityId: string) => {
    // TODO: 调用API获取区县数据
    try {
        const response = await $locationList({ id: cityId })
        districts.value = response.data;
        // 保存城市名
        hotelLocation.cityLocation = cities.value[cityId].name
        console.log(hotelLocation.cityLocation);
        hotelForm.district = '';
        hotelLocation.regionLocation = ''
    } catch (error) {
        console.error('获取区县数据失败:', error);
    }
}

const fetchDistricts1 = async (cityId: string) => {
    // TODO: 调用API获取区县数据
    try {
        const response = await $locationList({ id: cityId })
        districts.value = response.data;
        // 保存城市名
        travelLocation.cityLocation = cities.value[cityId].name
        console.log(hotelLocation.cityLocation);
        travelForm.district = '';
        hotelLocation.regionLocation = ''
    } catch (error) {
        console.error('获取区县数据失败:', error);
    }
}

// 添加区县选择事件处理器
const handleDistrictChange = (districtId: string) => {
    hotelLocation.regionLocation = districts.value[districtId].name
    console.log(hotelLocation.regionLocation);
}

const handleDistrictChange1 = (districtId: string) => {
    travelLocation.regionLocation = districts.value[districtId].name
}

// 在组件挂载时获取省份数据
onMounted(() => {
    fetchProvinces();
    fetchProvinces1();
});

const maxDescLength = 200

const hotelRules = rules
const hostelRules = rules


const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleImageChange = (uploadFile: any, uploadFiles: any[]) => {
    // 检查文件大小
    const isLt2M = uploadFile.raw.size / 1024 / 1024 < 2
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        // 从文件列表中移除超大文件
        const index = uploadFiles.indexOf(uploadFile)
        if (index !== -1) {
            uploadFiles.splice(index, 1)
        }
        return false
    }

    // 创建文件阅读器预览图片
    const reader = new FileReader()
    reader.onload = (e) => {
        if (e.target?.result) {
            uploadFile.url = e.target.result
        }
    }
    reader.readAsDataURL(uploadFile.raw)
}
const handleImagePreview = (file: any) => {
    dialogImageUrl.value = file.url
    dialogVisible.value = true
}

const handleImageRemove = (file: any, fileList: any[]) => {
    console.log('removed file', file, fileList)
    // 可以在这里处理文件移除后的逻辑
}


// 提交表单时处理图片上传
// const uploadImages = async (files: any[]) => {
//     const formData = new FormData()
//     files.forEach((file, index) => {
//         formData.append('images', file.raw)
//     })

//     try {
//         // 这里替换成您的实际上传API
//         const response = await fetch('https://api.example.com/upload', {
//             method: 'POST',
//             body: formData
//         })
//         const result = await response.json()
//         return result.imageUrls // 假设服务器返回图片URL数组
//     } catch (error) {
//         console.error('图片上传失败:', error)
//         throw error
//     }
// }

// 提交表单方法
// 修改提交表单方法
const submitHotelForm = async () => {
    if (!hotelFormRef.value) return
    await hotelFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 创建 FormData 对象
                let fd = new FormData()

                // 添加表单数据
                Object.keys(hotelForm).forEach(key => {
                    if (key !== 'hotelImage') { // 跳过图片数组
                        fd.append(key, hotelForm[key])
                    }
                })

                // 添加地区名称
                //fd.append('hotelLocation', JSON.stringify(hotelLocation))
                // 将 hotelLocation 中的每个字段单独传递
                Object.keys(hotelLocation).forEach(key => {
                    fd.append(`hotelLocation.${key}`, hotelLocation[key]);
                });


                // 检查是否有图片上传
                if (hotelForm.hotelImage.length === 0) {
                    ElMessage.error('请上传图片')
                    return
                }

                // 将所有图片文件添加到同一个数组字段
                hotelForm.hotelImage.forEach((file, index) => {
                    if (file.raw) {
                        fd.append('hotelImage', file.raw) // 使用相同的字段名 'hotelImage'
                    }
                })

                // 调用API提交数据
                const response = await $addHotel(fd)
                if (response.code === 2001) {
                    ElMessage({
                        type: 'success',
                        message: '酒店入驻申请提交成功'
                    })
                    resetHotelForm()
                } else {
                    ElMessage.error('提交失败，请联系管理员')
                }

            } catch (error) {
                ElMessage.error('表单提交失败，请重试')
                console.error(error)
            }
        }
    })
}
//旅行社表单提交
const submitTravelForm = async () => {
    if (!travelFormRef.value) return
    await travelFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 创建 FormData 对象
                let fd = new FormData()

                // 添加表单数据
                Object.keys(travelForm).forEach(key => {
                    if (key !== 'travelImage') { // 跳过图片数组
                        fd.append(key, travelForm[key])
                    }
                })

                // 添加地区信息
                Object.keys(travelLocation).forEach(key => {
                    fd.append(`travelLocation.${key}`, travelLocation[key]);
                });

                // 检查必要的图片是否上传
                // if (travelForm.licenseImages.length === 0) {
                //     ElMessage.error('请上传营业执照等必要证件')
                //     return
                // }

                // 添加所有证件图片
                travelForm.travelImage.forEach((file) => {
                    if (file.raw) {
                        fd.append('travelImages', file.raw)
                    }
                })

                // 调用API提交数据
                const response = await $addTravel(fd)
                if (response.code === 2001) {
                    ElMessage({
                        type: 'success',
                        message: '旅行社入驻申请提交成功'
                    })
                    resetTravelForm()
                } else {
                    ElMessage.error('提交失败，请联系管理员')
                }

            } catch (error) {
                ElMessage.error('表单提交失败，请重试')
                console.error(error)
            }
        }
    })
}
// 重置表单方法
const resetHotelForm = () => {
    if (!hotelFormRef.value) return
    hotelFormRef.value.resetFields()
}

const resetTravelForm = () => {
    if (!travelFormRef.value) return
    travelFormRef.value.resetFields()
}

</script>
<style scoped>
.content {
    padding: 32px;
    max-width: 900px;
    margin: 0 auto;
}

.custom-tabs {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.settled-form {
    padding: 24px;
}

:deep(.el-form-item) {
    margin-bottom: 24px;
}

:deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px #dcdfe6;
}

:deep(.el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #409eff;
}

:deep(.el-textarea__inner) {
    min-height: 120px !important;
}

.form-buttons {
    margin-top: 36px;
    text-align: center;
}

.submit-btn {
    padding: 12px 36px;
    font-size: 16px;
}

.reset-btn {
    padding: 12px 36px;
    font-size: 16px;
    margin-left: 16px;
}

.region-selectors {
    display: flex;
    gap: 12px;
}

:deep(.el-tabs__header) {
    margin-bottom: 0;
}

:deep(.el-tabs__nav) {
    padding: 0 20px;
}

:deep(.el-select) {
    width: 120px;
}
</style>
